package cn.liyunqi.ttv.web.common;

import cn.liyunqi.core.common.Constants;
import cn.liyunqi.core.exception.BizException;
import cn.liyunqi.core.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class RequestMap {

	private static Log logger = LogFactory.getLog(RequestMap.class);


	public static final boolean REQUIRED = true;
	public static final boolean NOTREQUIRED = false;

	private HttpServletRequest request;
	
	public RequestMap(HttpServletRequest request){
		this.request = request;
	}
	
	public String getStringValue(String key,String name , boolean isMust) throws BizException{
		String value = request.getParameter(key);
		if(value == null || value.trim().isEmpty() || "undefined".equals(value.trim().toLowerCase())){
			if(isMust){
				String msg = name + Message.ERROR_002;
				throw new BizException(msg);
			}else if(value != null){
				value = Constants.EMPTY;
			}
		}else{
			value = value.trim();
		}
		logger.info("参数"+key+"["+name+"]::" + value);
		return value;
	}
	public String getStringValue(String key,String name , boolean isMust,String defaultValue) throws BizException{
		String value = request.getParameter(key);
		if(value == null || value.trim().isEmpty()){
			if(isMust){
				String msg = name + Message.ERROR_002;
				throw new BizException(msg);
			}else{
				return defaultValue;
			}
		}else{
			value = value.trim();
		}
		logger.info("参数"+key+"["+name+"]::" + value);
		return value;
	}
	public BigDecimal getBigDecimalValue(String key,String name , boolean isMust) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return null;
		}
		BigDecimal decValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return null;
			}
			
			decValue = new BigDecimal(value);
			
		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return decValue;
	}
	public Integer getIntegerValue(String key,String name , boolean isMust) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return null;
		}
		Integer intValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return null;
			}
			
			intValue = Integer.valueOf(value);
			
		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return intValue;
	}
	public Float getFloatValue(String key,String name , boolean isMust) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return null;
		}
		Float fltValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return null;
			}

			fltValue = Float.valueOf(value);

		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return fltValue;
	}


	public Integer getIntegerValue(String key,String name , boolean isMust,Integer defaultValue) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return defaultValue;
		}
		Integer intValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return defaultValue;
			}

			intValue = Integer.valueOf(value);

		} catch (Exception e) {
			return defaultValue;
		}
		return intValue;
	}
	public Long getLongValue(String key,String name , boolean isMust) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return null;
		}
		Long lngValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return null;
			}
			
			lngValue = Long.valueOf(value);
			
		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return lngValue;
	}
	public Long getLongValue(String key,String name , boolean isMust,Long defalutValue) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return defalutValue;
		}
		Long lngValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return defalutValue;
			}
			
			lngValue = Long.valueOf(value);
			
		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return lngValue;
	}
	public Double getDoubleValue(String key,String name , boolean isMust) throws BizException{
		String value = getStringValue(key,name,isMust);
		if(value == null || value.trim().isEmpty()){
			return null;
		}
		Double douValue = null;
		try {
			if(StringUtil.isEmptyOrNull(value)){
				return null;
			}
			douValue = Double.valueOf(value);
			
		} catch (Exception e) {
			throw new BizException(name + "数据不合法！");
		}
		return douValue;
	}
	public <T> T getObjectVo(String key,String name ,boolean isMust ,Class<T> clazz) throws BizException{
		String value = request.getParameter(key);
		if(isMust){
			if(value == null || value.trim().isEmpty()){
				String msg = name + Message.ERROR_002;
				throw new BizException(msg);
			}
		}

		T t= JSONObject.parseObject(value, clazz);			
		if(isMust && t == null){
			String msg = name + Message.ERROR_002;
			throw new BizException(msg);
		}
		logger.info("参数"+key+"["+name+"]::" + value);

		return t;
	}

	public <T> List<T> getObjectListVo(String key,String name ,boolean isMust ,Class<T> clazz) throws BizException{
		String value = request.getParameter(key);
		if(isMust){
			if(value == null || value.trim().isEmpty()){
				String msg = name + Message.ERROR_002;
				throw new BizException(msg);
			}
		}
		List<T> list = JSONArray.parseArray(value, clazz);
		if(isMust && (list == null || list.size() == 0)){
			String msg = name + Message.ERROR_002;
			throw new BizException(msg);
		}
		if(list == null){
			list = new ArrayList<T>();
		}
		logger.info("参数"+key+"["+name+"]::" + value);

		return list;
	}
	public void setSessionAttribute(String name,Object obj){
		request.getSession().setAttribute(name, obj);
	}
	
	public Object getSessionAttribute(String name){
		return request.getSession().getAttribute(name);
	}
	
	public HttpSession getSession(){
		return request.getSession();
	}
	
	public String getURL(){
		return request.getRequestURI();
	}


	/**
	 * 获取当前ip
	 * @return
	 */
	public String getUserIP(){
		String ip = request.getHeader("X-Forwarded-For");  
        if (logger.isInfoEnabled()) {  
            logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);  
        }  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("WL-Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_CLIENT_IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getRemoteAddr();  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);  
                }  
            }  
        } else if (ip.length() > 15) {  
            String[] ips = ip.split(",");  
            for (int index = 0; index < ips.length; index++) {  
                String strIp = (String) ips[index];  
                if (!("unknown".equalsIgnoreCase(strIp))) {  
                    ip = strIp;  
                    break;  
                }  
            }  
        }  
        return ip; 
	}
}
